package com.fly.trading.controller;

import java.time.Duration;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fly.trading.dao.TradingUserRepository;
import com.fly.trading.entity.TradingUser;

@Controller
@RequestMapping("/user")
public class UserController
{
    @Autowired
    TradingUserRepository tradingUserRepository;
    
    /**
     * Spring WebFlux支持使用老的Spring MVC注解声明Reactive Controller<br>
     * Reactive Controller操作的是非阻塞的ServerHttpRequest和ServerHttpResponse
     * 
     * @param model
     * @return
     */
    @GetMapping("/add")
    public String add(Model model)
    {
        String name = RandomStringUtils.randomAlphabetic(5);
        tradingUserRepository.save(new TradingUser(name, "fullName: " + name)).block(Duration.ofSeconds(3));
        return "redirect:/list";
    }
    
    @GetMapping("delete/{id}")
    public String delete(@PathVariable String id, Model model)
    {
        tradingUserRepository.deleteById(id).block(Duration.ofSeconds(3));
        model.addAttribute("users", tradingUserRepository.findAll());
        return "redirect:/list";
    }
    
    @GetMapping("update/{id}")
    public String update(@PathVariable String id, Model model)
    {
        TradingUser user = tradingUserRepository.findById(id).block(Duration.ofSeconds(3));
        if (user != null)
        {
            user.setUserName("update to " + RandomStringUtils.randomAlphabetic(5));
            user.setFullName(user.getUserName());
            tradingUserRepository.save(user).block(Duration.ofSeconds(3));
        }
        return "redirect:/list";
    }
}